/// [Quadratic primes](https://projecteuler.net/problem=27)
/// when n=0, f(a,b,n)=b > 1
/// when n=1, f(a,b,n)=a+b+1 > 1, a > -b
/// when n=40,f(a,b,n)=40a+b+1600 > 1, a > 1/40 - (b/40 + 40)
fn main() {
    let mut max_index = (0, 0);
    let mut max_value = 0;
    for b in 2..=1000 {
        for a in -(b / 40 + 40)..1000 {
            let tmp = number_consecutive_primes(a, b);
            if tmp > max_value {
                max_index = (a, b);
                max_value = tmp;
            }
        }
    }
    println!(
        "{:4}: {} x {} = {}",
        max_value,
        max_index.0,
        max_index.1,
        max_index.0 * max_index.1
    );
}

fn number_consecutive_primes(a: isize, b: isize) -> usize {
    let mut n = 0;
    while is_prime(n * n + n * a + b) {
        n += 1;
    }
    n as usize
}

fn is_prime(n: isize) -> bool {
    if n <= 1 {
        return false;
    }
    let n = n as usize;
    let mut m = 2_usize;
    while m.pow(2) <= n {
        if n % m == 0 {
            return false;
        }
        m += 1;
    }
    true
}

#[cfg(test)]
mod test {
    use super::*;
    #[test]
    fn is_work() {
        assert_eq!(number_consecutive_primes(1, 41), 40);
        assert_eq!(number_consecutive_primes(-79, 1601), 80);
    }
}
